package alo.p10.work;

/**
 * @ClassName LinkedListMergeSort
 * @Description 链表排序
 * @Author Fanxc
 * @DATE 2021/3/12 15:54
 * @Version 1.0
 */
public class LinkedListMergeSort {
    class ListNode {
        int val;
        ListNode next;
        ListNode(int val) { this.val = val; }
    }
    public ListNode sortList(ListNode head) {
        if (head == null || head.next == null)
            return head;

        //分为两个链表
        ListNode fast = head.next, slow = head;
        while (fast != null && fast.next != null) {
            slow = slow.next;
            fast = fast.next.next;
        }
        ListNode tmp = slow.next;
        slow.next = null;

        ListNode left = sortList(head);
        ListNode right = sortList(tmp);

        return merge(left, right);
    }

    private ListNode merge(ListNode left, ListNode right) {
        //归并
        ListNode h = new ListNode(0);
        //哑结点
        ListNode res = h;
        while (left != null && right != null) {
            if (left.val < right.val) {
                h.next = left;
                left = left.next;
            } else {
                h.next = right;
                right = right.next;
            }
            h = h.next;
        }
        h.next = left != null ? left : right;
        return res.next;
    }


}
